import { Drawer, Dropdown, Menu, Message, Modal } from '@arco-design/web-react'
import { IconDown, IconFolderAdd, IconPlus } from '@arco-design/web-react/icon'
import React from 'react'
import { IApiItem, IGroupItem } from '../../../../utils/interfaces'
import { randomStr } from '../../../../utils/random'
import { apiStore } from '../../../../utils/store/apiStore'
import EditApi from '../EditApi'
import AddGroupModal from './AddGroupModal'
import ApiItems from './ApiItems'
import GroupTabs, { IGroupTabsRef } from './GroupTabs'
import { useGroup } from './useGroup'
import CodeGenerate from '../CodeGenerate'

export interface IGroupListRef {
    updateGroupData: () => void
    updateApiItems: () => void
    setEditingApi: (apiItem: IApiItem) => void
}

export interface IGroupListProps {
    groupListRef?: React.RefObject<IGroupListRef | null>
}

const GroupList: React.FC<IGroupListProps> = ({ groupListRef }) => {
    // 组数据
    const { apiItems, groupId, updateGroupId, updateApiItems } = useGroup()
    // 正在编辑的api项
    const [editingApi, setEditingApi] = useState<IApiItem | null>(null)
    // 添加分组对话框是否显示
    const [addGroupVisible, setAddGroupVisible] = useState(false)
    // groupTabs ref
    const groupTabsRef = useRef<IGroupTabsRef | null>(null)

    // 添加api的时候
    const handleAddApi = () => {
        const newApi: IApiItem = {
            id: randomStr(),
            label: '',
            type: 'api',
            method: 'GET',
            url: '',
            parentId: groupId,
        }
        setEditingApi(newApi)
    }

    // 添加分组
    const handleAddGroupOk = async (name: string) => {
        const newGroup: IGroupItem = {
            id: randomStr(),
            label: name,
            type: 'group',
            parentId: groupId,
        }

        await apiStore.save(newGroup)
        setAddGroupVisible(false)
        groupTabsRef?.current?.updateGroupData()
    }

    // 删除api
    const handleDeleteApi = (id: string) => {
        Modal.confirm({
            title: '确定要删除吗？',
            content: '删除后不可恢复',
            okButtonProps: {
                status: 'danger',
            },
            onOk: () => {
                return apiStore
                    .deleteApiItem(id)
                    .then(() => {
                        Message.success('删除成功')
                        updateApiItems(groupId)
                    })
                    .catch((e: string) => {
                        Message.error(`删除失败 ${e}`)
                        throw e
                    })
            },
        })
    }

    if (groupListRef) {
        groupListRef.current = {
            updateGroupData: () => groupTabsRef?.current?.updateGroupData(),
            updateApiItems: () => updateApiItems(groupId),
            setEditingApi: (apiItem: IApiItem) => setEditingApi(apiItem),
        }
    }

    return (
        <div>
            {/* 一个组 */}
            {/* tabs */}
            <div className='flex justify-between'>
                <GroupTabs
                    className='mb-2'
                    onSelectedGroupChange={(id) => updateGroupId(id)}
                    groupTabsRef={groupTabsRef}
                />
                {/* 添加按钮 */}
                <Dropdown.Button
                    onClick={handleAddApi}
                    trigger='click'
                    droplist={
                        <Menu>
                            <Menu.Item
                                onClick={() => setAddGroupVisible(true)}
                                key='1'
                                className='flex items-center'
                            >
                                <IconFolderAdd fontSize={20} className='mr-2' />
                                添加分组
                            </Menu.Item>
                        </Menu>
                    }
                    icon={<IconDown />}
                >
                    <IconPlus /> 添加API
                </Dropdown.Button>
            </div>
            {/* 内容 */}
            <ApiItems
                apiItems={apiItems}
                onDeleteApi={handleDeleteApi}
                onEditApi={setEditingApi}
                onNeedUpdate={() => updateApiItems(groupId)}
            />
            {/* 代码生成 */}
            <CodeGenerate className='mt-2 min-h-[200px] min-w-[500px] max-w-[80vw] mx-auto mb-8' apiItems={apiItems} />
            {/* 编辑API */}
            <Drawer
                title='编辑'
                visible={!!editingApi}
                onCancel={() => setEditingApi(null)}
                width='80%'
                footer={null}
                unmountOnExit={true}
            >
                {!!editingApi && (
                    <EditApi
                        apiItem={editingApi}
                        onUpdated={async () => {
                            await updateApiItems(groupId)
                            setEditingApi(null)
                        }}
                    />
                )}
            </Drawer>
            {/* 添加分组对话框 */}
            <AddGroupModal
                visible={addGroupVisible}
                onCancel={() => setAddGroupVisible(false)}
                onOk={({ name }) => handleAddGroupOk(name)}
            />
        </div>
    )
}

export default GroupList
